<?php
//patikrinimui ar puslapaia atveriami taip kaip reikia
if (!defined("OK")) { header("HTTP/1.0 404 Not Found"); }

// Isvalyti URL, pries XSS simbolius server'io globaliuose kintamuosiuose
function cleanurl($url) {
	$bad_entities = array("&", "\"", "'", '\"', "\'", "<", ">", "(", ")","\\");
	$safe_entities = array("&amp;", "", "", "", "", "", "", "", "", "");
	$url = str_replace($bad_entities, $safe_entities, $url);
	return $url;
/*
	$masyvas = array (
		"&" => "&amp;",
		"\"" => "",
		"'" => "",
		'\"' => "",
		"\'" => "",
		"<" => "",
		">" => "",
		"(" => "",
		")" => "",
		"\\"  => ""
	);
	
	return strtr($url, $masyvas);
*/
}

// Sutvarkyti $_SERVER globals
if (isset($PHP_SELF)) $PHP_SELF = cleanurl($_SERVER['PHP_SELF']);
if (isset($_SERVER['QUERY_STRING'])) $_SERVER['QUERY_STRING'] = cleanurl($_SERVER['QUERY_STRING']);
if (isset($_SERVER['REQUEST_URI'])) $_SERVER['REQUEST_URI'] = cleanurl($_SERVER['REQUEST_URI']);

// Nuorodos i iprastas
if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING']))
	$_GET = $url = url_arr($_SERVER['QUERY_STRING']);
else
	$_GET = $url = array();

function mysql_query1($query) {
	global $db;
	$result = $db->masyvas($query);
	return $result;
}

function galune($skaicius, $vienas, $du, $desim) {
	if (substr($skaicius,-1,1) == 0 || (substr($skaicius,-2,2) >= 10 && substr($skaicius,-2,2) <= 20)) return $desim;
	elseif (substr($skaicius,-1,1) >= 2 && substr($skaicius,-1,1) <= 9) return $du;
	else return $vienas;
}

// print_r with <pre> tag
function print_rr($info,$return=false) {
	$re = "<pre>";
	$re .= print_r($info, true);
	$re .= "</pre>";
	if ($return)
		return $re;
	else
		echo $re;
}

function http_get($host,$document = '/',$port = 80, $timeOut = 30){
	$out='';
	$res = '';
	$fp = fsockopen($host, $port, $errno, $errstr, $timeOut);
	if ($fp) {
		$out .= "GET {$document} HTTP/1.1\r\n";
		$out .= "Accept: */*\r\n";
		$out .= "Host: {$host}\r\n";
		$out .= "\r\n";

		fwrite($fp, $out);
		while (!feof($fp)) {
			$res .= fgets($fp, 128);
		}
		fclose($fp);
	}
	return $res;
}

//imam info is XML
function get_tag_contents($xml, $tag) {
	$result = "";
	$s_tag = "<$tag>";
	$s_offs = strpos($xml, $s_tag);

	// If we found a starting offset, then look for the end-tag.
	//
	if($s_offs) {
		$e_tag = "</$tag>";
		$e_offs = strpos( $xml, $e_tag, $s_offs );

		// If we have both tags, then dig out the contents.
		//
		if($e_offs)
			$result = substr($xml, $s_offs + strlen( $s_tag ), $e_offs - $s_offs - strlen( $e_tag ) + 1);
	}
	return $result;
}

//Suskaičiuojam kiek nurodytoje lentelėje yra įrašų
function kiek($table, $where = '', $as = "viso") {
	global $db;
	$viso = $db->masyvas($db->uzklausa("SELECT count(*) AS $as FROM $table $where",__file__,__line__));
	if ($viso) return $viso[$as];
	else return false;
}
/*
//Perkeliau i MySQL klase
function kiek($table_where) {
	global $db;
	return $db->rows($db->uzklausa("SELECT * FROM ".$table_where));
}
*/
//puslapiavimui
function puslapiai($start,$count,$total,$range=0,$link="") {
	$res="";
	$pg_cnt=ceil($total / $count);
	if ($pg_cnt > 1) {
		$idx_back = $start - $count;
		$idx_next = $start + $count;
		$cur_page=ceil(($start + 1) / $count);
		$res.="<div style=\"text-align: center; font-size: 12px;\">\n";
		//$res.="<span class='sarasas'>Puslapis $cur_page iš $pg_cnt\n";
		if ($idx_back >= 0) {
			if ($cur_page > ($range + 1)) $res.="<a href='".url("p,0")."'>[<u>««</u>]</a>\n";
			$res.="<a href='".url("p,$idx_back")."'><u>Ankstesnis</u></a>\n";
		}
		$idx_fst=max($cur_page - $range, 1);
		$idx_lst=min($cur_page + $range, $pg_cnt);
		if ($range==0) {
			$idx_fst = 1;
			$idx_lst=$pg_cnt;
		}
		for($i=$idx_fst;$i<=$idx_lst;$i++) {
			$offset_page=($i - 1) * $count;
			if ($i==$cur_page) {
				$res.="<font color='red'>[<u><b>$i</b></u>]</font>\n";
			} else {
				$res.="<a href='".url("p,$offset_page")."'>[<u>$i</u>]</a>\n";
			}
		}
		if ($idx_next < $total) {
			$res.="<a href='".url("p,$idx_next")."'><u>Kitas</u></a>\n";
			if ($cur_page < ($pg_cnt - $range)) {
				$res.="<a href='".url("p,".($pg_cnt-1)*$count)."'><u>»»</u></a>\n";
			}
		}
		//$res.="</span>\n";
		$res.="</div>\n";

	}
	return $res;
}

/**
 * Tikrina ar kintamasis yra teigiamas skaičius
 *
 * @param num $value
 * @return 1 or NULL
 */
function isNum($value) {
	if (!is_array($value)) { return (preg_match("/^[0-9]+$/", $value)); } 
	else { return false; }
}

function random_name($i=10) {
	$chars = "abcdefghijkmnopqrstuvwxyz023456789";
	srand((double)microtime()*1000000);
	$name = '' ;
	while ($i >= 0) {
		$num = rand() % 33;
		$tmp = substr($chars, $num, 1);
		$name = $name . $tmp;
		$i--;
	}
	return $name;
}

//Sutvarko SQL užklausa
function escape($sql) {
	if (QUOTES) {
		$sql = stripslashes($sql);
	}
	$sql = "'" . mysql_real_escape_string($sql) . "'";
	return $sql;
}

//Paruošiam stringą saugiam atvaizdavimui
function input($s) {
	return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}

/**
 * Adreso apdorojimui
 *
 * @param $_SERVER['QUERY_STRING'] $params
 * @return array
 */
function url_arr($params) {
	$params = explode(";", $params);
	$str2 = array();
	foreach ($params as $key => $value) {
		$str1 = explode(",", $value);
		if (isset($str1[1])) $str2[$str1[0]] = $str1[1];
	}
	return $str2;
}

//Iš masyvo padarom nuorodą (sena versija)
function arr_url1($arr) {
	$return = '';
	if (is_array($arr)) {
		$str = '';
		foreach ($arr as $key => $value) {
			if (strlen($value) != 0) {
				$return .= $str.$key.','.$value;
			}
			$str = ';';
		}
	}
	return $return;
}

//Iš masyvo padarom nuorodą (V2 - dekui: "sliekas_kanibalas" uz patobulinimą)
function arr_url($params,$str='') {
	$strs = array();
	foreach ($params as $key => $value) {       
		$strs[] = $key . ',' . rawurlencode($value);
	}
	$str .= implode(";", $strs);
	return $str;
}

// Nuorodų apdorojimas
function url($str,$link="") {
	global $url, $_SERVER;
	if (empty($_SERVER['QUERY_STRING'])) {
		$url = array();
	}
	if (!is_array($str)) {
		$str = url_arr($str);
	}
	return $link."?".arr_url(array_merge($url,$str));
}


//Peradresavimo budai
function perkelti($location, $type="header") {
	if ($type == "header") {
		header("Location: ".$location); exit;
	} elseif ($type == "meta") {
		echo "<meta http-equiv='Refresh' content='0;url=$location'>";
	} elseif ($type == "letai") {
		echo "<meta http-equiv='Refresh' content='100;url=$location'>";
	} else {
		echo "<script type='text/javascript'>document.location.href='".$location."'</script>\n";
	}
}

function amzius($data) {
	if (!isset($data) || $data == '' || $data == '0000-00-00') { return "- N/A"; }
		else {
		$data = explode ("-", $data);
		$amzius = time() - mktime(0,0,0,$data['1'],$data['2'],$data['0']);
		$amzius = date("Y",$amzius) - 1970;
		return $amzius;
	}
}

function descript($text,$striptags=true) {
	// Convert problematic ascii characters to their true values
	$search = array("40","41","58","65","66","67","68","69","70",
		"71","72","73","74","75","76","77","78","79","80","81",
		"82","83","84","85","86","87","88","89","90","97","98",
		"99","100","101","102","103","104","105","106","107",
		"108","109","110","111","112","113","114","115","116",
		"117","118","119","120","121","122","239"
		);
	$replace = array("(",")",":","a","b","c","d","e","f","g","h",
		"i","j","k","l","m","n","o","p","q","r","s","t","u",
		"v","w","x","y","z","a","b","c","d","e","f","g","h",
		"i","j","k","l","m","n","o","p","q","r","s","t","u",
		"v","w","x","y","z",""
		);
	$entities = count($search);
	for ($i=0;$i < $entities;$i++) $text = preg_replace("#(&\#)(0*".$search[$i]."+);*#si", $replace[$i], $text);
	$text = str_replace(chr(32).chr(32), "&nbsp;", $text);
	$text = str_replace(chr(9), "&nbsp; &nbsp; &nbsp; &nbsp;", $text);
	// the following is based on code from bitflux (http://blog.bitflux.ch/wiki/)
	// Kill hexadecimal characters completely
	$text = preg_replace('#(&\#x)([0-9A-F]+);*#si', "", $text);
	// remove any attribute starting with "on" or xmlns
	$text = preg_replace('#(<[^>]+[\\"\'\s])(onmouseover|onmousedown|onmouseup|onmouseout|onmousemove|onclick|ondblclick|onload|xmlns)[^>]*>#iU', ">", $text);
	// remove javascript: and vbscript: protocol
	$text = preg_replace('#([a-z]*)=([\`\'\"]*)script:#iU', '$1=$2nojscript...', $text);
	$text = preg_replace('#([a-z]*)=([\`\'\"]*)javascript:#iU', '$1=$2nojavascript...', $text);
	$text = preg_replace('#([a-z]*)=([\'\"]*)vbscript:#iU', '$1=$2novbscript...', $text);
        //<span style="width: expression(alert('Ping!'));"></span> (only affects ie...)
	$text = preg_replace('#(<[^>]+)style=([\`\'\"]*).*expression\([^>]*>#iU', "$1>", $text);
	$text = preg_replace('#(<[^>]+)style=([\`\'\"]*).*behaviour\([^>]*>#iU', "$1>", $text);
	if ($striptags) {
		do {
	        $thistext = $text;
			$text = preg_replace('#</*(applet|meta|xml|blink|link|style|script|iframe|frame|frameset|ilayer|layer|bgsound|title|base)[^>]*>#i', "", $text);
		} while ($thistext != $text);
	}
	return $text;
}

function isImage1($matches) {
	$img = $matches[1].str_replace(array("?","&","="),"",$matches[3]).$matches[4];
	$img = $matches[1].$matches[3].$matches[4];
	if (@getimagesize($img)) {
		$res = "<img src='".$img."' style='border:0px;'>";
	}
	else {
		$res = "[img]".$img."[/img]";
	}
	return $res;
}

//Sulaužom žodį jei perilgas - laužo net ir jei žodis turi tarpus
function wrap1($text,$chars=25) {
        $text = wordwrap($text, $chars, "<br />\n", 1);
        return $text;
}

//Sulaužo žodi tik jei jis yra be tarpu ir perilgas
function wrap($string,$width,$break="\n") {
	$string = preg_replace('/([^\s]{'.$width.'})/i',"$1$break",$string);
	return $string;
}

//Tikrinam ar kintamasis sveikas skaičius ar normalus žodis
function tikrinam ($txt) {
	return (preg_match("/^[0-9a-zA-Z]+$/",$txt));
}

//bano galiojimo laikas. Rodo data iki kada +30 dienu
//echo "Galioja iki: ".galioja('12', '19', '2007');
//grazina: Galioja iki: 2008-01-17
function galioja($menuo,$diena,$metai,$kiek_galioja=30) {
	$nuo = (int)(mktime(0,0,0,$menuo,$diena,$metai)- time(void)/86400);
	$liko = $nuo + ($kiek_galioja * 24 * 60 * 60);
	return date('Y-m-d',$liko);
}
function liko($diena, $menuo, $metai){
	$until = mktime(0,0,0,$menuo,$diena,$metai);
	$now = time();
	$difference = $until - $now;
	$days = floor($difference/86400);
	$difference = $difference - ($days*86400);
	$hours = floor($difference/3600);
	$difference = $difference - ($hours*3600);
	$minutes = floor($difference/60);
	$difference = $difference - ($minutes*60);
	$seconds = $difference;
	return (int)$days + 1;
}

//sutvarko url iki linko
function linkas($str) {
	$str = strtolower(strip_tags($str));
	//return preg_replace_callback("#([\n ])([a-z]+?)://([a-z0-9\-\.,\?!%\*_\#:;~\\&$@\/=\+]+)#si", "linkai", $str);
	return preg_replace("`((http)+(s)?:(//)|(www\.))((\w|\.|\-|_)+)(/)?(\S+)?`i", "<a href=\"http://\\5\\6\" title=\"\\0\" target=\"_blank\" class=\"link\" >\\5\\6</a>", $str);
}

// apvalinti:
// suapvalina nurodyta skaičiu
// (išesmės veikia kaip ceil() tik leidžia nurodyti dešimtainę)
function apvalinti($sk, $kiek) {
	if ($kiek < 0) { $kiek = 0; }
	$mult = pow(10, $kiek);
	return ceil($sk * $mult) / $mult;
} 

function naujas($data,$nick=null) {
	global $ses;
	if (isset($ses->user_data['lankesi']) && $nick != $ses->user_data['username']) {
		return (($data > $ses->user_data['lankesi']) ? '<font color=red><b>Naujas</b></font>' : '');
	} else {
		return "";
	}
}

//Pries kiek laiko
function kada($laikas) {
	if ($laikas == '' || $laikas == "0000-00-00 00:00:00") { return ""; }
	if(!isnum($laikas)) $laikas = strtotime($laikas);
	if (isset($laikas{9})) $skirtumas = time() - $laikas;
	else $skirtumas = $laikas;
	
	//7 * 24 * 60 * 60
	if(604800 > $skirtumas) {
		if(86400 > $skirtumas) {
			if(3600 > $skirtumas) {
				if(60 > $skirtumas) {
					return "prieš ".$skirtumas."s.";
				} else {
					return "prieš ".(floor($skirtumas / 60))."min.";
				}
			} else {
				return "prieš ".(floor($skirtumas / 3600))."val.";
			}
		} else {
			return "prieš ".(floor($skirtumas / 86400))."d.";
		}
	} else {
		return "prieš ".(floor($skirtumas / 604800))."sav. $laikas";
	}
	//$kazkas  = date ("Y n W j, G i:s", $skirtumas);
	//return "$kazkas";
	/*
	$mins = floor((time() - $ts / 60);
	$hours = floor($mins / 60);
	$mins -= $hours * 60;
	$days = floor($hours / 24);
	$hours -= $days * 24;
	$weeks = floor($days / 7);
	$days -= $weeks * 7;
	$month = floor($weeks / 4);
	$days -= $month * 4;
	$year = floor($month  / 12);
	$days -= $year * 12;
	if ($year)
		return "prieš ".$year ." ". ($year > 1 ? "m." : "m.");
	if ($month)
		return "prieš ".$month ." ". ($month > 1 ? "mėn." : "mėn.");
	if ($weeks)
		return "prieš ".$weeks ." ". ($weeks > 1 ? "sav." : "sav.");
	if ($days)
		return "prieš ".$days ." ". ($days > 1 ? "d." : "d.");
	if ($hours)
		return "prieš ".$hours ." ". ($hours > 1 ? "val." : "val.");
	if ($mins)
		return "prieš ".$mins ." ". ($mins > 1 ? "min." : "min.");
		return "prieš < 1 minutę";
	*/
}
$lang = array();
$lang['datetime']['Sunday'] = 'Sekmadienis';
$lang['datetime']['Monday'] = 'Pirmadienis';
$lang['datetime']['Tuesday'] = 'Antradienis';
$lang['datetime']['Wednesday'] = 'Trečiadienis';
$lang['datetime']['Thursday'] = 'Ketvirtadienis';
$lang['datetime']['Friday'] = 'Penktadienis';
$lang['datetime']['Saturday'] = 'Šeštadienis';
$lang['datetime']['Sun'] = 'Sk.';
$lang['datetime']['Mon'] = 'Pir.';
$lang['datetime']['Tue'] = 'Antr.';
$lang['datetime']['Wed'] = 'Tr.';
$lang['datetime']['Thu'] = 'Kv.';
$lang['datetime']['Fri'] = 'Pen.';
$lang['datetime']['Sat'] = 'Št.';
$lang['datetime']['January'] = 'Sausis';
$lang['datetime']['February'] = 'Vasaris';
$lang['datetime']['March'] = 'Kovas';
$lang['datetime']['April'] = 'Balandis';
$lang['datetime']['May'] = 'Gegužė';
$lang['datetime']['June'] = 'Birželis';
$lang['datetime']['July'] = 'Liepa';
$lang['datetime']['August'] = 'Rugpjūtis';
$lang['datetime']['September'] = 'Rugsėjis';
$lang['datetime']['October'] = 'Spalis';
$lang['datetime']['November'] = 'Lapkritis';
$lang['datetime']['December'] = 'Gruodis';
$lang['datetime']['Jan'] = '01';
$lang['datetime']['Feb'] = '02';
$lang['datetime']['Mar'] = '03';
$lang['datetime']['Apr'] = '04';
$lang['datetime']['May'] = '05';
$lang['datetime']['Jun'] = '06';
$lang['datetime']['Jul'] = '07';
$lang['datetime']['Aug'] = '08';
$lang['datetime']['Sep'] = '09';
$lang['datetime']['Oct'] = '10';
$lang['datetime']['Nov'] = '11';
$lang['datetime']['Dec'] = '12';
//create_date("j", mktime(0, 0, 0, (int) $config['men'], (int) $config['diena'], (int) $config['metai']) - time(), 3);
//create_date("j", $time, 3)
function create_date($format, $gmepoch, $tz) {
	global $lang;
	static $translate;
	reset($lang['datetime']);
	while ( list($match, $replace) = each($lang['datetime']) ) {
			$translate[$match] = $replace;
	}

	return strtr(gmdate($format, $gmepoch + (3600 * $tz)), $translate);
}

//vercia baitus i zmoniu kalba
function baitai($size,$digits=2,$dir=false) {
    $kb=1024; $mb=1024*$kb; $gb=1024*$mb; $tb=1024*$gb;
    if (($size==0)&&($dir)) { return " Nulis"; }
    elseif ($size<$kb) { return $size." Baitai"; }
    elseif ($size<$mb) { return round($size/$kb,$digits)." Kb"; }
    elseif ($size<$gb) { return round($size/$mb,$digits)." Mb"; }
    elseif ($size<$tb) { return round($size/$gb,$digits)." Gb"; }
    else { return round($size/$tb,$digits)." Tb"; }
}

// Trim a line of text to a preferred length
function trimlink($text, $length) {
	$dec = array("\"", "'", "\\", '\"', "\'", "<", ">");
	$enc = array("&quot;", "&#39;", "&#92;", "&quot;", "&#39;", "&lt;", "&gt;");
	$text = str_replace($enc, $dec, $text);
	if (strlen($text) > $length) $text = substr($text, 0, ($length-3))."...";
	$text = str_replace($dec, $enc, $text);
	return $text;
}

//Paskaiciuojam procentus
function procentai($reikia,$yra,$zenklas=false) {
	$return = (int)round((100 * $yra) / $reikia);
	if ($return > 100 && $zenklas) {
		$return = "<img src='images/icons/accept.png' class='middle' alt='100%' title='100%' borders='0' />";
	} elseif ($return > 0 && $zenklas) {
		$return = "<img src='images/icons/cross.png' class='middle' alt='".$return."%' title='".$reikia."/".$yra." - ".$return."%' borders='0' />";
	}
	return $return;
}

//Insert SQL - supaprastina duomenu iterpima, paduodam lentles pavadinima ir kitu argumentu asociatyvu masyva
function insert($table,$array) {
	return 'INSERT INTO `'.$table.'` ('.implode(', ',array_keys($array)).') VALUES ('.implode(', ',array_map('escape',$array)).')';
}

//echo "<img src='".pic('http://img95.imageshack.us/img95/6290/web1160860226jy1.jpg')."'>";
function pic($off_site,$size=150,$url='images/nuorodu/',$sub='url') {
	if (!file_exists($url.$sub."_".basename($off_site))) {
		if (pic1($off_site,$size)) {
			return $url.$sub."_".basename($off_site);
		}
		else { return $url."noimage.jpg"; }
	}
	else {
		return $url.$sub."_".basename($off_site);
	}
}

function pic1($off_site,$size=150,$download=true,$url='images/nuorodu/',$sub='url') {
	$fp = @fopen($off_site, 'rb'); $buf = '';
	if ($fp) {
		while (!feof ($fp)) {
			$buf .= fgets($fp, 4096);
		}
	
		$data = $buf;
	
		//naujas aukštis
		$src = @imagecreatefromstring ($data);
		if (empty($src)) { return false; }
		$width = @imagesx($src);
		$height = @imagesy($src);
		$aspect_ratio = $width/$height;
	
		//keičiam dydį
		if ($width <= $size) {
			$new_w = $width;
			$new_h = $height;
		} else {
			$new_w = $size;
			$new_h = @abs($new_w/$aspect_ratio);
		}
	
		$img = @imagecreatetruecolor ($new_w,$new_h);
	
		//atvaizduojam paveiksliuką
		@imagecopyresampled ($img,$src,0,0,0,0,$new_w,$new_h,$width,$height);
	
		$file = $url.$sub."_".basename($off_site);
		
		//nustatom paveiksliuko tipą ir gražinam naršyklei
		$z = @imagejpeg($img, $file, 90);
		@imagedestroy($img);
		unset($buf);
	}
}

//Grąžina failo galūnę
function ext($file_name) {
	return strrchr($file_name,".");
}

function botas($agentas) {
	if (preg_match("/\bGigabot\b/i", $agentas)) return true;
	if (preg_match("/\bmsnbot\b/i", $agentas)) return true;
	if (preg_match("/\bgoogle\b/i", $agentas)) return true;
	if (preg_match("/\bIRLbot\b/i", $agentas)) return true;
	if (preg_match("/\bHostTracker\b/i", $agentas)) return true;
	if (preg_match("/\bEasyDL\b/i", $agentas)) return true;
	if (preg_match("/\be-collector\b/i", $agentas)) return true;
	if (preg_match("/\bEmailCollector\b/i", $agentas)) return true;
	if (preg_match("/\bTelesoft\b/i", $agentas)) return true;
	if (preg_match("/\bTwiceler\b/i", $agentas)) return true;
	/*
	if (preg_match("/^Mozilla/\d\.\d\s\(compatible;\sAdvanced\sEmail\sExtractor\sv\d\.\d+\)$/", $agentas)) return true;
	if (preg_match("/\bCherryPicker\b/i", $agentas)) return true;
	if (preg_match("/\bCrescent\b/i", $agentas)) return true;
	if (preg_match("/^DA\s\d\.\d+$/", $agentas)) return true;
	if (preg_match("/^Mozilla/\d\.\d\s\(compatible;\sMSIE\s\d\.\d;\sWindows\sNT;\sDigExt;\sDTS\sAgent$/", $agentas)) return true;
	if (preg_match("/^EmailSiphon$/", $agentas)) return true;
	if (preg_match("EmailWolf", $agentas)) return true;
	if (preg_match("ExtractorPro", $agentas)) return true;
	if (preg_match("Go!Zilla", $agentas)) return true;
	if (preg_match("GetRight/\d.\d", $agentas)) return true;
	if (preg_match("/^ia_archiver$/", $agentas)) return true;
	if (preg_match("Indy\sLibrary", $agentas)) return true;
	if (preg_match("larbin", $agentas)) return true;
	if (preg_match("MSIECrawler", $agentas)) return true;
	if (preg_match("Microsoft\sURL\sControl", $agentas)) return true;
	if (preg_match("NEWT\sActiveX", $agentas)) return true;
	if (preg_match("NICErsPRO", $agentas)) return true;
	if (preg_match("RealDownload/\d\.\d\.\d\.\d", $agentas)) return true;
	if (preg_match("Teleport", $agentas)) return true;
	if (preg_match("UtilMind\sHTTPGet", $agentas)) return true;
	if (preg_match("WebBandit", $agentas)) return true;
	if (preg_match("webcollage/\d\.\d\d", $agentas)) return true;
	if (preg_match("WebCopier\sv\d\.\d", $agentas)) return true;
	if (preg_match("WebEMailExtrac", $agentas)) return true;
	if (preg_match("WebZIP", $agentas)) return true;
	if (preg_match("/^WGet/\d\.\d", $agentas)) return true;
	if (preg_match("/^Zeus.+Webster", $agentas)) return true;
	if (preg_match("/^Mozilla/3\.Mozilla/2\.01\s\(Win95;\sI\)$/", $agentas)) return true;
	if (preg_match("/^Internet\sExplorer\s?\d?\.?\d?$/", $agentas)) return true;
	if (preg_match("/^IE\s\d\.\d\sCompatible.*Browser$/", $agentas)) return true;
	if (preg_match("/^Microsoft\sInternet\sExplorer/4\.40\.426\s\(Windows\s95\)$/", $agentas)) return true;
	if (preg_match("/^SurveyBot/\d\.\d\s(<a\shref='http://www\.whois\.sc'>Whois\sSource</a>|\(Whois\sSource\))$/", $agentas)) return true;
	if (preg_match("/^Mozilla/4\.0\s\(?hhjhj@yahoo\.com\)?$/", $agentas)) return true;
	if (preg_match("/^MSIE", $agentas)) return true;
	if (preg_match("/^Mozilla$/", $agentas)) return true;
	if (preg_match("/^Mozilla(\\|/)\?\?$/", $agentas)) return true;
	if (preg_match("/^Internet\sExplore\s?\d?\.?[a-z0-9]+$/", $agentas)) return true;
	if (preg_match("/^IAArchiver-\d\.\d$/", $agentas)) return true;
	if (preg_match("/^NPBot(-\d/\d\.\d)?(\s\(http://www\.nameprotect\.com/botinfo\.html\))?$/", $agentas)) return true;
	if (preg_match("/^Webclipping\.com$/", $agentas)) return true;
	if (preg_match("/^Mozilla/\d\.\d\s\(X11;\sLinux\si686;\sen-US;\srv:\d.\d[a-z0-9]*;\sOBJR\)$/", $agentas)) return true;
	if (preg_match("/^Sqworm/\d\.\d\.\d\d-BETA\s\(beta_release;\s\d{8}-\d{3};\si\d{3}-pc-linux-gnu\)$/", $agentas)) return true;
	if (preg_match("/^Lickity_Split/\d\.\d$/", $agentas)) return true;
	if (preg_match("/^Production\sBot\s\d+B$/", $agentas)) return true;
	if (preg_match("/^amzn_assoc$/", $agentas)) return true;
	if (preg_match("/^Harvest", $agentas)) return true;
	if (preg_match("/^Webdup/\d\.\d$/", $agentas)) return true;
	if (preg_match("/^WebIndex/\d\.\d[a-z]$/", $agentas)) return true;
	if (preg_match("(/^|\s)RPT-HTTPClient/\d\.\d-\d$/", $agentas)) return true;
	if (preg_match("/^sitecheck\.internetseer\.com\s\(For\smore\sinfo\ssee:\shttp://sitecheck\.internetseer\.com\)$/", $agentas)) return true;
	if (preg_match("/^vspider$/", $agentas)) return true;
	if (preg_match("/^k2spider$/", $agentas)) return true;
	if (preg_match("/^Mac\sFinder\s", $agentas)) return true;
	if (preg_match("/^ICU\sv", $agentas)) return true;
	if (preg_match("/^DART$/", $agentas)) return true;
	if (preg_match("/^Mozilla/\d\.\d\s\(compatible;\sMSIE\s\d\.\d;\sWindows\sNT\s\d\.\d;\sQ\d{6};\s\.NET\sCLR\s\d\.\d\.\d{4}$/", $agentas)) return true;
	if (preg_match("/^COMBOMANIA$/", $agentas)) return true;
	if (preg_match("/^MyCrawler$/", $agentas)) return true;
	if (preg_match("/^Mozilla/\d\.\d\s\(compatible;\sWin32;\sWinHttp\.WinHttpRequest\.\d\)$/", $agentas)) return true;
	if (preg_match("/^WEP\sSearch\s\d+$/", $agentas)) return true;
	if (preg_match("/^Mozilla/\d\.\d\s\(fantomBrowser\)$/", $agentas)) return true;
	if (preg_match("/^TE$/", $agentas)) return true;
	if (preg_match("/^WebStripper/\d\.\d\d$/", $agentas)) return true;
	if (preg_match("/^OWR_Crawler\s\d\.\d$/", $agentas)) return true;
	if (preg_match("/^WebMiner/\d\.\d\s\[en\]\s\(Win\d\d;\sI\)$/", $agentas)) return true;
	if (preg_match("/^WebGather\s\d\.\d$/", $agentas)) return true;
	if (preg_match("/^readwebpage$/", $agentas)) return true;
	if (preg_match("/^InstantSSL\sBrowser:\slow\scost\sfully\svalidated\sSSL\s\+\sfree\strial$/", $agentas)) return true;
	if (preg_match("/^Mozilla/\d\.\d\s\(compatible;\sHTTrack\s2\.0x;\sWindows\s.+\)$/", $agentas)) return true;
	if (preg_match("/^Mozilla/4\.0\s\(compatible;\sPowermarks/\d\.\d;\sWindows\s.+\)$/", $agentas)) return true;
	if (preg_match("/^Vivante\sLink\sChecker\s\(http://www\.vivante\.com\)$/", $agentas)) return true;
	if (preg_match("/^Mozilla/\d\.\d\s\(compatible;\sWindows\sNT\s\d\.\d;\sABN\sAMRO$/", $agentas)) return true;
	if (preg_match("/^Mozilla/\d\.\d\s\(compatible;\sIntelliseek;\shttp://www\.intelliseek\.com\)$/", $agentas)) return true;
	if (preg_match("/^WebCopier\sSession\s\d$/", $agentas)) return true;
	if (preg_match("/^Mozilla/\d\.\d\s\(compatible;\sMSIE\s\d\.\d\d;\sWindows\s\d\d$/", $agentas)) return true;
	if (preg_match("/^Art-Online\.com\s\d\.\d\(Beta\)$/", $agentas)) return true;
	if (preg_match("/^WebGo\s", $agentas)) return true;
	if (preg_match("/^SuperBot/\d\.\d\s\(Win\d\d\)$/", $agentas)) return true;
	if (preg_match("/^Download\sNinja\s\d\.\d$/", $agentas)) return true;
	if (preg_match("/^Mozilla/\d\.\d\s\(compatible;\sMSIE\s\d\.\d;\sWindows\sNT\s\d\.\d;\s\.NET\sCLR\s\d\.\d\.\d{4}$/", $agentas)) return true;
	if (preg_match("/^Expired\sDomain\sSleuth$/", $agentas)) return true;
	if (preg_match("/^SHARP-TQ-GX\d\d$/", $agentas)) return true;
	if (preg_match("/^HTTP/\d\.\d\sMozilla/\d\.\d\+\(compatible;\+MSIE\+\d\.\d;\+Windows\+NT\+\d\.\d\)$/", $agentas)) return true;
	if (preg_match("/^.+/\d+\.\d+\s\(Version:\s\d+\sType:\d+\)$/", $agentas)) return true;
	if (preg_match("/^Offline\sExplorer/\d+\.\d+$/", $agentas)) return true;
	*/
	else { return false; }
}


function bbs($forma) {
	return smile("
		:-)
		;-)
		:-]
		:-D
		:o
		:-o
		:(
		B-)
		:-|
		:P
		>)
		o_0
		",$forma)."<br/>";
}

//SYPSENOS
function smile($data,$bb = FALSE) {
        $smilies = array(
				':)' => 'smile.gif',
				':]' => 'razz.gif',
				':-)' => 'smile.gif',
				';-)' => 'wink.gif',
				';)' => 'wink.gif',
				':-]' => 'biggrin.gif',
				':-D' => '003.gif',
				':D' => '003.gif',
				':o' => 'shock.gif',
				':-o' => '103.gif',
				':O' => 'confuse.gif',
				':(' => 'cry.gif',
				'B-)' => 'cool.gif',
				'B)' => 'cool.gif',
				'%-)' => 'cool.gif',
				':-|' => 'neutral.gif',
				':|' => 'neutral.gif',
				':P' => '118.gif',
				':p' => '118.gif',
				'>)' => 'badgrin.gif',
				'0_o' => '119.gif',
				'o_0' => '119.gif',
				);
		foreach($smilies as $smile => $image) {
			$data = str_replace($smile,"<img src='images/smiles/$image' alt='$smile' class='middle' ".(($bb)?"onclick=\"addText('".$bb."','".$smile."',' ');\" style=\"cursor: pointer;\"":"")." />",$data);
		}
	return $data;
}

//bbcodo varijantas 1
function bb2html($Input) {
  $Bbcode = array
  (
    '/\[b\](.+?)\[\/b\]/i',
    '/\[i\](.+?)\[\/i\]/i',
    '/\[quote\](.+?)\[\/quote\]/i',
    '/\[url=(.+?)\](.+?)\[\/url\]/i'
  );
  $Html = array
  (
    '<strong>$1</strong>',
    '<em>$1</em>',
    '<blockquote>$1</blockquote>',
    '<a href="$1">$2</a>'
  );
  return preg_replace($Bbcode, $Html, $Input);
}



// bbcode

function nl2br2( $text ) {
	return str_replace( '<br />', '', $text );
}
function htmlspecialchars2( $text ) {
    static $patterns, $replaces;
    if( !$patterns ){
        $patterns = array( '#&lt;#', '#&gt;#', '#&amp;#', '#&quot;#' );
        $replaces = array( '<', '>', '&', '"' );
    }
    return preg_replace( $patterns, $replaces, $text );
}
function bbchat($str) {

	//$str=htmlspecialchars(trim($str));
	$str=descript($str);
	// paryskinam teksta
	$str = preg_replace("#\[b\](.*?)\[/b\]#si", "<b>\\1</b>", $str);
	// Paverciam teksta
	$str = preg_replace("#\[i\](.*?)\[/i\]#si", "<i>\\1</i>", $str);
	// Pabraukiam teksta
	$str = preg_replace("#\[u\](.*?)\[/u\]#si", "<u>\\1</u>", $str);
	// Mazas sriftas
	$str = preg_replace("#\[sm\](.*?)\[/sm\]#si", "<small>\\1</small>", $str);
	// Specialus simboliai
	$str = str_replace('&amp;plusmn;', '&plusmn;', $str);
	$str = str_replace('&amp;trade;', '&trade;', $str);
	$str = str_replace('&amp;bull;', '&bull;', $str);
	$str = str_replace('&amp;deg;', '&deg;', $str);
	$str = str_replace('&amp;copy;', '&copy;', $str);
	$str = str_replace('&amp;reg;', '&reg;', $str);
	$str = str_replace('&amp;hellip;', '&hellip;', $str);
	$str = str_replace('&amp;#8230;', '&hellip;', $str);
	// Konvertuojam naujas eilutes i <br/>
	$str=nl2br($str);
	//padarom grazias kabutes
	$str = preg_replace("#\&quot;(.+?)\&quot;#si", "<q>\\1</q>", $str);
	//$str = preg_replace("/\"(.+?)\"/i", "<q>\\1</q>", $str);

	// js
	$str = preg_replace_callback("#\<(.*?)javascript(.*?)\>#si", "bbcode_js", $str);

	return $str;
}

function bbcode($str) {
	// Problemos su \ slashais
	//$str=str_replace("\\","&#92;",$str);
	//$str = preg_replace('&','#&amp;#',$str);
	$str=input($str);
	$str = preg_replace("#\[php\](.*?)\[\/php\]#sie", "base64encode('<textarea name=\"code\" class=\"php\" rows=\"15\" cols=\"100\">\\1</textarea>')", $str);
	$str = preg_replace("#\[mirc\](.*?)\[\/mirc\]#sie", "base64encode('<textarea name=\"code\" class=\"mirc\" rows=\"15\" cols=\"100\">\\1</textarea>')", $str); 
	$str = preg_replace("#\[html\](.*?)\[\/html\]#sie", "base64encode('<textarea name=\"code\" class=\"html\" rows=\"15\" cols=\"100\">\\1</textarea>')", $str); 
	$str = preg_replace("#\[css\](.*?)\[\/css\]#sie", "base64encode('<textarea name=\"code\" class=\"css\" rows=\"15\" cols=\"100\">\\1</textarea>')", $str); 
	$str = preg_replace("#\[js\](.*?)\[\/js\]#sie", "base64encode('<textarea name=\"code\" class=\"js\" rows=\"15\" cols=\"100\">\\1</textarea>')", $str); 
	$str = preg_replace("#\[sql\](.*?)\[\/sql\]#sie", "base64encode('<textarea name=\"code\" class=\"sql\" rows=\"15\" cols=\"100\">\\1</textarea>')", $str); 

	// Atverciam linka naujame lange
	$str = preg_replace("#\[url\](.*?)?(.*?)\[/url\]#si", "<a href=\"\\1\\2\" target=\"_blank\" class=\"link\">\\1\\2</A>", $str);
	$str = preg_replace("#\[url=(.*?)?(.*?)\](.*?)\[/url\]#si", "<a href=\"\\2\" target=\"_blank\" class=\"link\">\\3</A>", $str);

	// Atverciam linka tame paciame lange
	$str = preg_replace("#\[url2\](.*?)?(.*?)\[/url2\]#si", "<a href=\"\\1\\2\">\\1\\2</A>", $str);
	$str = preg_replace("#\[url2=(.*?)?(.*?)\](.*?)\[/url2\]#si", "<a href=\"\\2\">\\3</A>", $str);

	// Automatiskai konvertuojam nuorodas
	$str = preg_replace_callback("#([\n ])([a-z]+?)://([a-z0-9\-\.,\?!%\*_\#:;~\\&$@\/=\+]+)#si", "bbcode_autolink", $str);
	//$str = preg_replace("#([\n ])www\.([a-z0-9\-]+)\.([a-z0-9\-.\~]+)((?:/[a-z0-9\-\.,\?!%\*_\#:;~\\&$@\/=\+]*)?)#i", " <a href=\"http://www.\\2.\\3\\4\" target=\"_blank\">www.\\2.\\3\\4</a>", $str);
	$str = preg_replace("#([\n ])([a-z0-9\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)?[\w]+)#i", "\\1<a href=\"javascript:mailto:mail('\\2','\\3');\">\\2_(at)_\\3</a>", $str);

	
	// Slepti tekstui - rodomas tik registruotiems vartotojams
	$id = uniqid();
	if(PRISIJUNGES)
		$str = preg_replace("#\[hide=\"?(.*?)\"?\](.*?)\[/hide]#si", "<a href=\"#\" onclick=\"flip(\'' . $id . '\'); return false;\"><font color=\"red\">▲</font> <b>\\1</b> <font color=\"red\">▼</font></a><div id=\"' . $id . '\" class=\"ukryj\" style=\"display: none;\">\\2</div>", $str);
	else
		$str = preg_replace("#\[hide=\"?(.*?)\"?\](.*?)\[/hide]#si", "<a href=\"#\" onclick=\"flip(\'' . $id . '\'); return false;\"><font color=\"red\">▲</font> <b>\\1</b> <font color=\"red\">▼</font></a><div id=\"' . $id . '\" class=\"ukryj\" style=\"display: none;\">Tik registruotiems vartotojams</div>", $str);

	//$str = preg_replace_callback("#\[hide=\"?(.*?)\"?\](.*?)\[/hide]#si", 'ShowOnlyLogedIn', $str);


	// Paryskinam teksta
	$str = preg_replace("#\[b\](.*?)\[/b\]#si", "<b>\\1</b>", $str);

	// Paverciam teksta
	$str = preg_replace("#\[i\](.*?)\[/i\]#si", "<i>\\1</i>", $str);

	// Pabraukiam teksta
	$str = preg_replace("#\[u\](.*?)\[/u\]#si", "<u>\\1</u>", $str);

	// Mazas tekstas
	$str = preg_replace("#\[sm\](.*?)\[/sm\]#si", "<small>\\1</small>", $str);

	// Didelis tekstas
	$str = preg_replace("#\[big\](.*?)\[/big\]#si", "<big>\\1</big>", $str);

	// Centruojam
	$str = preg_replace("/\[center\](.*?)\[\/center\]/si", "<center>\\1</center>", $str);

	// Spalvojam teksta
	$str = preg_replace("#\[color=(http://)?(.*?)\](.*?)\[/color\]#si", "<span style=\"color:\\2\">\\3</span>", $str);

	// Rodom paveiksliuka
	$str = preg_replace("/\[img\](http:\/\/[^\s'\"<>]+(\.gif|\.jpg|\.png))\[\/img\]/", "<img border=0 src=\"\\1\" alt=\"pic\" onError=\"this.src='images/icons/nopic.png';this.style.border='1px dashed red';this.style.margin='5px';this.style.padding='5px'\">", $str);
	$str = preg_replace("/\[img\](http:\/\/[^\s'\"<>]+(\.GIF|\.JPG|\.PNG))\[\/img\]/", "<img border=0 src=\"\\1\" alt=\"pic\" onError=\"this.src='images/icons/nopic.png';this.style.border='1px dashed red';this.style.margin='5px';this.style.padding='5px'\">", $str);

	// [img=http://www/image.gif]
	$str = preg_replace("/\[img=(http:\/\/[^\s'\"<>]+(\.gif|\.jpg|\.png))\]/", "<img border=0 src=\"\\1\">", $str);
	$str = preg_replace("/\[img=(http:\/\/[^\s'\"<>]+(\.GIF|\.JPG|\.PNG))\]/", "<img border=0 src=\"\\1\">", $str);

	// Cituojam
	$str = preg_replace("#\[quote\](.*?)\[/quote]#si", "<p class=\"cytat\"><u><b>Citata:</b></u><br/>\\1</p>", $str);

	// Cituojam autoriu
	$str = preg_replace("#\[quote=(http://)?(.*?)\](.*?)\[/quote]#si", "<p class=\"cytat\"><u><b>\\2 rašė:</b></u><br/>\\3</p>", $str);

	// Sarašas
	$str = preg_replace("#\[list\](.*?)\[/list\]#si", "<ul>\\1</ul>", $str);
	$str = preg_replace("#\[list=(http://)?(.*?)\](.*?)\[/list\]#si", "<ol type=\"\\2\">\\3</ol>", $str);
	$str = preg_replace("#\[\*\](.*?)\\s#si", "<li>\\1</li>", $str);

	// Atvaizduojam emailą
	$str = preg_replace("#\[email\]([a-z0-9\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)?[\w]+)\[/email\]#i", "<a href=\"mailto:\\1@\\2\">\\1@\\2</a>", $str);

	// HTML formavimas
	$str=nl2br($str);
	$str = str_replace("[br]","<br/>",$str);
	$str = smile($str);
		
	// Iskvieciam kodu atvaizdavima
	$str = preg_replace_callback("#\<base64\>(.*?)\</base64\>#si","base64_decode", $str);
	
	return $str;
}

// Emailo apsauga
function bbcode_js($str){
	if(!eregi('<a href=\"javascript:mailto:mail\(\'',$str[0])){
		return str_replace('javascript','java_script',$str[0]);
	} else{
		return $str[0];
	}
}

// Sutrumpinta nuoroda
function bbcode_autolink($str){
	$lnk=$str[3];
	if(strlen($lnk)>30){
		if(substr($lnk,0,3) == 'www') $l = 9;
		else $l = 5;
		$lnk=substr($lnk,0,$l).'...'.substr($lnk,strlen($lnk)-8);
	}
	return ' <a href="'.$str[2].'://'.$str[3].'" target="_blank" class="link"> '.$str[2].'://'.$lnk.' </a>';
}


function bbk($forma) {
	$return = "
	<script>document.body.addKeyDown(66, function() {if (window.event.ctrlKey) alert(\"CTRL + B\");});</script>
<button onclick=\"addText('$forma', '[b]', '[/b]'); return false;\" title=\"B\"><img src=\"images/icons/text_bold.png\"></button>
<button onclick=\"addText('$forma', '[i]', '[/i]'); return false;\" title=\"I\"><img src=\"images/icons/text_italic.png\"></button>
<button onclick=\"addText('$forma', '[u]', '[/u]'); return false;\" title=\"U\"><img src=\"images/icons/text_underline.png\"></button>
<button onclick=\"addText('$forma', '[url]', '[/url]'); return false;\" title=\"URL\"><img src=\"images/icons/link.png\"></button>
<button onclick=\"addText('$forma', '[big]', '[/big]'); return false;\" title=\"BIG\"><img src=\"images/icons/text_heading_1.png\"></button>
<button onclick=\"addText('$forma', '[sm]', '[/sm]'); return false;\" title=\"SM\"><img src=\"images/icons/text_heading_6.png\"></button>
<button onclick=\"addText('$forma', '[br]', ''); return false;\" title=\"BR\"><img src=\"images/icons/arrow_undo.png\"></button>
<button onclick=\"addText('$forma', '[img]', '[/img]'); return false;\" title=\"IMG\"><img src=\"images/icons/picture.png\"></button>
<button onclick=\"addText('$forma', '[quote]', '[/quote]'); return false;\" title=\"QUOTE\"><img src=\"images/icons/comment.png\"></button> | 
<button onclick=\"addText('$forma', '[mirc]', '[/mirc]'); return false;\" title=\"mIRC\"><img src=\"images/icons/page_white_code_red.png\"></button>
<button onclick=\"addText('$forma', '[html]', '[/html]'); return false;\" title=\"HTML\"><img src=\"images/icons/page_white_h.png\"></button>
<button onclick=\"addText('$forma', '[php]', '[/php]'); return false;\" title=\"PHP\"><img src=\"images/icons/page_white_php.png\"></button>
<button onclick=\"addText('$forma', '[js]', '[/js]'); return false;\" title=\"JS\"><img src=\"images/icons/page_white_cup.png\"></button>
<button onclick=\"addText('$forma', '[css]', '[/css]'); return false;\" title=\"CSS\"><img src=\"images/icons/page_white_c.png\"></button>
<button onclick=\"addText('$forma', '[sql]', '[/sql]'); return false;\" title=\"SQL\"><img src=\"images/icons/page_white_database.png\"></button>
";
	if (ADMIN == 1) { $return .= "\n<button onclick=\"addText('$forma', '[hide=Tik registruotiems]', '[/hide]'); return false;\" title=\"HIDE\"><img src=\"images/icons/shield.png\"></button>\n"; }
	return $return."<br />";
}

// Atkoduojam koda
//function base64decode($str){
//	return base64_decode($str[1]);
//}

// Užkoduojam kodą
function base64encode($str){
	return "<base64>".base64_encode($str)."</base64>";
}
?>
